package com.qls.mt.biz.common.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.util.Random;

/**
 * @author doyoung
 */
@Slf4j
public class MtClient {
    private static final String VERSION = "1.0";
    private static final Random RANDOM = new Random();

    private void setBaseParam(FxBaseApiRequest request) {
        request.setVersion(VERSION);
        request.setTimestamp(System.currentTimeMillis() / 1000);
        request.setNonce(RANDOM.nextInt(Integer.MAX_VALUE));
        request.setSignature(calculateSignature(request));
    }

    private String calculateSignature(FxBaseApiRequest request) {

        // 计算签名
        String rawSignStr = "accesskey=" + request.getAccesskey() + "&data=" + request.getData()
                + "&method=" + request.getMethod() + "&nonce=" + request.getNonce()
                + "&partnerId=" + request.getPartnerId() + "&timestamp=" + request.getTimestamp()
                + "&version=" + request.getVersion();
        return this.hmacSha1(rawSignStr, request.getSecretKey());
    }

    private String hmacSha1(String plainText, String secretKey) {
        SecretKeySpec secretKeySpec = new SecretKeySpec(StringUtils.getBytesUtf8(secretKey), "HmacSHA1");
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(secretKeySpec);
            return Base64.encodeBase64String(mac.doFinal(StringUtils.getBytesUtf8(plainText)));
        } catch (GeneralSecurityException var5) {
            throw new IllegalArgumentException(var5);
        }
    }

    public String post(FxBaseApiRequest request) {
        setBaseParam(request);
        String jsonString = JSON.toJSONString(request);
        String host = "https://fenxiao.meituan.com/opdtor/api";
        int count = 0;
        int max = 2;
        String result = null;
        while (true) {
            count++;
            try {
                result = HttpRequest.post(host)
                        .header("Content-Type", "application/json; charset=utf-8")
                        .header("Accept", "application/json")
                        .body(jsonString)
                        .timeout(20000)
                        .execute()
                        .body();
                break;
            } catch (Exception ignored) {
                if (count > max) {
                    break;
                }
            }
        }
        return result;
    }
}
